package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xydtech.common.EcardOrgInfoApiCommon;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.AESEncryptionUtils;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.common.utils.GeoUtil;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.config.service.IEcardApiSysConfigService;
import com.xydtech.ecard.ecard.domain.EcardApiAgricultureInfo;
import com.xydtech.ecard.ecard.domain.EcardApiMerchantPartInfo;
import com.xydtech.ecard.ecard.domain.EcardApiMerchantTask;
import com.xydtech.ecard.ecard.domain.EcardApiMerchantVisitInfo;
import com.xydtech.ecard.ecard.service.IEcardApiAgricultureInfoService;
import com.xydtech.ecard.ecard.service.IEcardApiMerchantPartInfoService;
import com.xydtech.ecard.ecard.service.IEcardApiMerchantTaskService;
import com.xydtech.ecard.ecard.service.IEcardApiMerchantVisitInfoService;
import com.xydtech.ecard.merchant.domain.*;
import com.xydtech.ecard.merchant.service.IEcardBranchAgricultureChartService;
import com.xydtech.ecard.user.domain.EcardApiEcardRegistInfo;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiEcardRegistInfoService;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.domain.SysConfig;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysConfigService;
import com.xydtech.system.service.ISysDeptService;
import com.xydtech.system.service.ISysUserService;
import com.xydtech.system.service.ISysWechatAppletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 电子名片-新型农业主体营销接口类
 *
 * @author yuzhiguo
 * @date 2024-08-19 上午10:41
 */
@Controller
@Slf4j
@Api(tags = "电子名片-新型农业主体营销接口")
@RequestMapping("/ecardSaasApi/agricultureMarketing")
public class EcardAgricultureMarketingController extends EcardApiBaseController{

    //4:客户经理
    private static String roles = "4";
    //客户经理岗位，后台没维护，这里用不到
    private static String cm = "cm";
    //网格管理员岗位
    private static String wg = "wg";

    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardApiAgricultureInfoService ecardAgricultureInfoService;
    @Autowired
    private IEcardApiEcardRegistInfoService registInfoService;
    @Autowired
    private IEcardApiMerchantVisitInfoService ecardMerchantVisitInfoService;
    @Autowired
    private ISysWechatAppletService wechatAppletService;
    @Autowired
    private IEcardApiSysConfigService ecardApiSysConfigService;
    @Autowired
    private IEcardApiMerchantTaskService ecardApiMerchantTaskService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IEcardApiMerchantPartInfoService ecardMerchantPartInfoService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IEcardBranchAgricultureChartService ecardBranchAgricultureChartService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private EcardOrgInfoApiCommon ecardOrgInfoApiCommon;

    /**
     * 电子名片-条件查询登录人名下新型农业主体列表接口
     *
     * @author yuzhiguo
     * @date 2024/8/19 上午11:00
     */
    @PostMapping(value = "/getMyAgricultureList")
    @ApiOperation(value = "电子名片-条件查询登录人名下新型农业主体列表接口", notes = "电子名片-条件查询登录人名下新型农业主体列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMyAgricultureList(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            JSONObject jsonObject = JSONObject.parseObject(json);
            //查询条件姓名和手机号拆开
            String agrCustName = jsonObject.getString("agrCustName");//姓名
            String agrCustPhone = jsonObject.getString("agrCustPhone");//联系方式
            Integer agrType = jsonObject.getInteger("agrType");//农业主体类型
            String agrLicenseName = jsonObject.getString("agrLicenseName");//营业执照名称
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");

            EcardApiAgricultureInfo ecardAgricultureInfo = new EcardApiAgricultureInfo();
            ecardAgricultureInfo.setAgrCustName(agrCustName);
            ecardAgricultureInfo.setAgrCustPhone(agrCustPhone);
            ecardAgricultureInfo.setAgrType(agrType);
            ecardAgricultureInfo.setAgrLicenseName(agrLicenseName);
            ecardAgricultureInfo.setManagementPersonnelId(Long.valueOf(currentUserId));
            ecardAgricultureInfo.setDictDeptId(wechatApplet.getDeptId());//字典机构查询条件
            PageHelper.startPage(pageNum, pageSize);
            List<EcardApiAgricultureInfo> agricultureList = ecardAgricultureInfoService.getMyAgricultureList(ecardAgricultureInfo, salt);
            List<EcardApiAgricultureInfo> apiAgricultureList = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(agricultureList);
            for (EcardApiAgricultureInfo agriculture : agricultureList) {
                //查询总拜访次数
                EcardApiMerchantVisitInfo merchantVisitInfo = new EcardApiMerchantVisitInfo();
                merchantVisitInfo.setMerchantId(agriculture.getId());
                merchantVisitInfo.setMerchantType("4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                List<EcardApiMerchantVisitInfo> visitInfoList = ecardMerchantVisitInfoService.getMerchantVisitList(merchantVisitInfo);
                agriculture.setVisitNumber(visitInfoList.size() + "");

                //查询最近一次拜访时间
                String lastVisitTime = ecardMerchantVisitInfoService.getMerchantLastVisitTime(agriculture.getId(), "4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                if (StringUtils.isNotEmpty(lastVisitTime)) {
                    agriculture.setLastVisitDate(DateUtils.parseDate(lastVisitTime));
                }
                apiAgricultureList.add(agriculture);
            }
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), apiAgricultureList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-条件查询新型农业主体列表接口
     *
     * @param: type 1登录人所在机构下全部，2法人机构下全部（针对网格管理岗位）
     * @param: search 查询条件
     * @author yuzhiguo
     * @date 2024/8/19 11:35
     */
    @PostMapping(value = "/getAgricultureList")
    @ApiOperation(value = "电子名片-条件查询新型农业主体列表接口", notes = "电子名片-条件查询新型农业主体列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getAgricultureList(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            //查询客户经理信息
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String type = jsonObject.getString("type");
            String search = jsonObject.getString("search");//查询条件姓名和手机号拆开
            Integer agrType = jsonObject.getInteger("agrType");//农业主体类型
            String sortTime = jsonObject.getString("sortTime");
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");

            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            EcardApiAgricultureInfo ecardAgricultureInfo = new EcardApiAgricultureInfo();
            ecardAgricultureInfo.setAgrCustName(search);
            ecardAgricultureInfo.setAgrType(agrType);
            ecardAgricultureInfo.setSortTime(sortTime);

            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            ecardAgricultureInfo.setDictDeptId(wechatApplet.getDeptId());//字典机构查询条件
            if (ecardApiEcardRegistInfo != null) {
                boolean postFlag = false;
                //多个岗位判断，只要有网格管理就传法人机构
                if (!StringUtils.objIsNullOrEmpty(userInfo.getExtendPostCode())) {
                    for (String extendPost : userInfo.getExtendPostCode().split(",")) {
                        if (wg.equals(extendPost)) {
                            postFlag = true;
                        }
                    }
                }
                if (roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                    if ("1".equals(type) && !postFlag) {
                        ecardAgricultureInfo.setDeptId(userInfo.getDeptId());
                    } else if (postFlag) {
                        //当前小程序对应的法人信息
                        ecardAgricultureInfo.setDeptId(wechatApplet.getDeptId());
                    } else {
                        return ResponseModel.error("操作人岗位不正确,请联系管理员！");
                    }
                } else {
                    return ResponseModel.error("您没有查看新型农业主体列表的权限！");
                }
            } else {
                return ResponseModel.error("用户信息不存在！");
            }
            PageHelper.startPage(pageNum, pageSize);
            List<EcardApiAgricultureInfo> agricultureList = ecardAgricultureInfoService.getAgricultureList(ecardAgricultureInfo);
            PageInfo pageInfo = new PageInfo(agricultureList);
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), agricultureList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询新型农业主体地图坐标列表接口
     *
     * @param: type 1登录人所在机构下全部，2法人机构下全部（针对网格管理岗位）
     * @author yuzhiguo
     * @date 2024/8/19 13:10
     */
    @PostMapping(value = "/getAgricultureCoordinateList")
    @ApiOperation(value = "电子名片-查询新型农业主体地图坐标列表接口", notes = "电子名片-查询新型农业主体地图坐标列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getAgricultureCoordinateList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            JSONObject jsonObject = JSONObject.parseObject(json);
            String type = jsonObject.getString("type");
            Integer agrType = jsonObject.getInteger("agrType");//农业主体类型
            String coordinate = jsonObject.getString("coordinate");

            SysConfig config = new SysConfig();
            config.setConfigKey("ecard_merchant_show_distance");
            SysConfig sysConfig;

            if (StringUtils.objIsNullOrEmpty(currentUserId) || StringUtils.objIsNullOrEmpty(type)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            List<EcardApiAgricultureInfo> ecardAgricultureList;
            if ("1".equals(type)) {
                //获取当前用户的信息
                EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
                ecardAgricultureList = ecardAgricultureInfoService.getAgricultureCoordinateList(Long.valueOf(currentUserId), userInfo.getDeptId(), agrType);
                SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
                config.setDeptId(sysDept.getDeptId());
                sysConfig = ecardApiSysConfigService.selectConfig(config);
            } else {
                EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
                //当前小程序id
                SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
                ecardAgricultureList = ecardAgricultureInfoService.getAllAgricultureCoordinateList(Long.valueOf(currentUserId), wechatApplet.getDeptId(), agrType);
                SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(wechatApplet.getDeptId());
                config.setDeptId(sysDept.getDeptId());
                sysConfig = ecardApiSysConfigService.selectConfig(config);
            }

            //有经纬度就计算，没有取全部
            if (coordinate != null) {
                List<EcardApiAgricultureInfo> list = new ArrayList<>();
                //计算是否在配置的范围之内
                //定位的新型农业主体经纬度
                String place[] = coordinate.split(",");
                for (EcardApiAgricultureInfo ecardApiAgricultureInfo : ecardAgricultureList) {
                    String clockInPlace[] = ecardApiAgricultureInfo.getAgrCoordinate().split(",");
                    Double distance = GeoUtil.GetDistance(Double.valueOf(clockInPlace[1]), Double.valueOf(clockInPlace[0]), Double.valueOf(place[1]), Double.valueOf(place[0]));

                    BigDecimal bigDistance = new BigDecimal(distance);
                    BigDecimal bigValue = new BigDecimal(sysConfig.getConfigValue());
                    if (bigDistance.compareTo(bigValue) <= 0) {
                        list.add(ecardApiAgricultureInfo);
                    }
                }
                return ResponseModel.okToJSONArray(list);
            } else {
                return ResponseModel.okToJSONArray(ecardAgricultureList);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询新型农业主体详情接口
     *
     * @author yuzhiguo
     * @date 2024/8/19 下午1:33
     */
    @PostMapping("/getAgricultureInfo")
    @ApiOperation(value = "电子名片-查询新型农业主体详情接口", notes = "电子名片-查询新型农业主体详情接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getAgricultureInfo(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);
            if (!roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                return ResponseModel.error("您没有查看该新型农业主体的权限！");
            }

            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }

            //根据新型农业主体id查询新型农业主体成员信息
            EcardApiMerchantPartInfo apiMerchantPartInfo = new EcardApiMerchantPartInfo();
            apiMerchantPartInfo.setMerchantId(id);
            apiMerchantPartInfo.setMerchantType("4");
            List<EcardApiMerchantPartInfo> merchantPartList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoList(apiMerchantPartInfo, salt);//商户类型：1-个人，2-商户，3-企业，4-新型农业主体

            EcardApiAgricultureInfo agricultureInfo = ecardAgricultureInfoService.selectEcardAgricultureInfoById(id, salt);
            //数据解密（手机号、身份证号）
            if (!StringUtils.objIsNullOrEmpty(agricultureInfo.getAgrCustPhone())) {
                agricultureInfo.setAgrCustPhone(AESEncryptionUtils.decrypt(agricultureInfo.getAgrCustPhone(), salt));
            }
            if (!StringUtils.objIsNullOrEmpty(agricultureInfo.getAgrCustIdcard())) {
                agricultureInfo.setAgrCustIdcard(AESEncryptionUtils.decrypt(agricultureInfo.getAgrCustIdcard(), salt));
            }
            if (merchantPartList.size() > 0) {
                agricultureInfo.setEcardApiMerchantPartInfos(merchantPartList);
            }
            return ResponseModel.okToJSON(agricultureInfo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-保存新型农业主体数据接口,只有客户经理能保存新型农业主体信息
     *
     * @author yuzhiguo
     * @date 2024/8/19 下午1:49
     */
    @PostMapping(value = "/addAgricultureInfo")
    @ApiOperation(value = "电子名片-保存新型农业主体数据接口", notes = "电子名片-保存新型农业主体数据接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addAgricultureInfo(@RequestBody EcardApiAgricultureInfo ecardAgricultureInfo) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            Long agrId = ecardAgricultureInfo.getId();//新型农业主体id
            boolean flag = false;//判断是新增还是编辑，true：新增，false：编辑
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            if (!roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                return ResponseModel.error("您没有编辑新型农业主体信息的权限！");
            }
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            //当前登录人ID
            ecardAgricultureInfo.setCreatorId(Long.valueOf(currentUserId));
            //管户人id
            ecardAgricultureInfo.setManagementPersonnelId(Long.valueOf(currentUserId));
            //登录人机构ID
            ecardAgricultureInfo.setDeptId(userInfo.getDeptId());
            if (!StringUtils.isNotNull(ecardAgricultureInfo.getId())) {
                /*int count = ecardAgricultureInfoService.validateAgricultureInfo(ecardAgricultureInfo);
                if (count > 0) {
                    return ResponseModel.error("相同主体类型、支行、新型农业主体名不能重复！");
                }*/
                flag = true;
            } else {
                //校验是否是自己的新型农业主体
                EcardApiAgricultureInfo ecardApiAgricultureInfo = ecardAgricultureInfoService.selectEcardAgricultureInfoById(ecardAgricultureInfo.getId(), salt);
                if (ecardApiAgricultureInfo != null) {
                    if (ecardApiAgricultureInfo.getManagementPersonnelId().longValue() != ecardApiEcardRegistInfo.getRegistId().longValue()) {
                        ResponseModel.error("您没有编辑该新型农业主体信息的权限！");
                    }
                } else {
                    return ResponseModel.error("操作失败，未查询到该新型农业主体信息！");
                }
                flag = false;
            }
            //数据加密（手机号、身份证号）
            if (!StringUtils.objIsNullOrEmpty(ecardAgricultureInfo.getAgrCustPhone())) {
                ecardAgricultureInfo.setAgrCustPhone(AESEncryptionUtils.encrypt(ecardAgricultureInfo.getAgrCustPhone(), salt));
            }
            if (!StringUtils.objIsNullOrEmpty(ecardAgricultureInfo.getAgrCustIdcard())) {
                ecardAgricultureInfo.setAgrCustIdcard(AESEncryptionUtils.encrypt(ecardAgricultureInfo.getAgrCustIdcard(), salt));
            }
            if (!StringUtils.objIsNullOrEmpty(ecardAgricultureInfo.getAgrPhoneNumber())) {
                ecardAgricultureInfo.setAgrPhoneNumber(AESEncryptionUtils.encrypt(ecardAgricultureInfo.getAgrPhoneNumber(), salt));
            }
            int id = ecardAgricultureInfoService.addAgricultureInfo(ecardAgricultureInfo);

            //处理成员信息（新增/编辑）
            List<EcardApiMerchantPartInfo> ecardApiMerchantPartInfos = ecardAgricultureInfo.getEcardApiMerchantPartInfos();
            if (ecardApiMerchantPartInfos.size() > 0) {
                for (EcardApiMerchantPartInfo ecardMerchantPartInfo : ecardApiMerchantPartInfos) {
                    if (!StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getIdCard())) {
                        EcardApiMerchantPartInfo merchantPartInfo = new EcardApiMerchantPartInfo();
                        merchantPartInfo.setMerchantId(ecardMerchantPartInfo.getMerchantId());
                        merchantPartInfo.setIdCard(ecardMerchantPartInfo.getIdCard());
                        merchantPartInfo.setMerchantType("4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                        List<EcardApiMerchantPartInfo> partInfoList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoList(merchantPartInfo, salt);
                        if (partInfoList != null && partInfoList.size() > 0) {
                            //判断是新增还是编辑
                            if (StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getId())) {
                                return ResponseModel.error("成员信息已存在！");
                            } else {
                                if (!partInfoList.get(0).getId().equals(ecardMerchantPartInfo.getId())) {
                                    return ResponseModel.error("成员信息已存在！");
                                }
                            }
                        }
                    }

                    //查询新型农业主体人员是否存在
                    if (!StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getId())) {
                        EcardApiMerchantPartInfo ecardApiMerchantPartInfo = ecardMerchantPartInfoService.selectEcardMerchantPartInfoById(ecardMerchantPartInfo.getId(), salt);
                        if (ecardApiMerchantPartInfo == null) {
                            return ResponseModel.error("成员信息不存在，请核实！");
                        }
                    }

                    //当前登录人Id
                    ecardMerchantPartInfo.setCreatorId(Long.valueOf(currentUserId));
                    ecardMerchantPartInfo.setMerchantType("4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                    if (flag){//新增时取保存完新型农业主体返回的新型农业主体id，编辑时取传参的新型农业主体id
                        ecardMerchantPartInfo.setMerchantId(ecardAgricultureInfo.getId());
                    } else {
                        ecardMerchantPartInfo.setMerchantId(agrId);
                    }
                    //添加时根据新型农业主体id和商户类型判断有没有成员，没有把是否联系人字段改为是，有不操作
                    List<EcardApiMerchantPartInfo> ecardMerchantPartInfos = ecardMerchantPartInfoService.getMerchantPartList(ecardMerchantPartInfo.getMerchantId(), "4", wechatApplet.getDeptId(), salt);
                    if (ecardMerchantPartInfos.size() == 0) {
                        ecardMerchantPartInfo.setIsContacts("T");
                    }
                    ecardMerchantPartInfoService.addMerchantPartInfo(ecardMerchantPartInfo, salt);
                }
            }
            if (flag) {//只有新增新型农业主体时添加拜访任务
                //查询参数配置-拜访任务定时天数
                SysConfig config = new SysConfig();
                config.setConfigKey("ecard_merchant_task_days");
                SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
                config.setDeptId(sysDept.getDeptId());
                SysConfig sysConfig = ecardApiSysConfigService.selectConfig(config);
                int taskDays = Integer.valueOf(sysConfig.getConfigValue());//拜访任务定时天数
                /**
                 * 保存新型农业主体时新增一条拜访任务，下次回访日期默认为当前日期加拜访任务定时天数
                 */
                Date nextDay = DateUtils.getNextDay(new Date(), taskDays);
                Date endDate = DateUtils.formatDate(nextDay, DateUtils.YYYY_MM_DD);
                EcardApiMerchantTask merchantTask = new EcardApiMerchantTask();
                merchantTask.setMerchantId(ecardAgricultureInfo.getId());
                merchantTask.setCmRegistId(ecardAgricultureInfo.getManagementPersonnelId());
                merchantTask.setMerchantType("4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                merchantTask.setEndDate(endDate);
                merchantTask.setTaskSts("0");
                ecardApiMerchantTaskService.insertEcardMerchantTask(merchantTask);
            }
            return id > 0 ? ResponseModel.ok(ecardAgricultureInfo.getId()) : ResponseModel.error("添加失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }


    }

    /**
     * 电子名片-调用天眼查接口模糊查询获取工商信息列表
     *
     * @author yuzhiguo
     * @date 2024/11/7 下午2:53
     */
    @PostMapping(value = "/getLikeAgricultureByTYC")
    @ApiOperation(value = "电子名片-调用天眼查接口模糊查询获取工商信息列表", notes = "电子名片-调用天眼查接口模糊查询获取工商信息列表")
    @ResponseBody
    @RsaRequest
    public ResponseModel getLikeAgricultureByTYC(@RequestBody String json) {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        //接口编号
        String apiNum = ecardApiSysConfigService.selectConfigByKey("data.interfaceNum.orgVagueSearch", dept.getDeptId());
        JSONObject jsonObject = JSONObject.parseObject(json);
        String agrLicenseName = jsonObject.getString("agrLicenseName");//营业执照名称
        if (StringUtils.objIsNullOrEmpty(agrLicenseName)) {
            return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
        }
        List<EcardApiAgricultureInfo> agricultureInfoList = new ArrayList<>();
        /**调用接口*/
        ResponseModel responseModel = ecardOrgInfoApiCommon.getOrgInfoByApi(userInfo, apiNum, agrLicenseName, "");
        if (responseModel.getCode() == 0) {
            JSONObject baseInfo = JSONObject.parseObject(JSON.toJSONString(responseModel.getData()));
            //获取工商数量
            int total = baseInfo.getIntValue("total");
            if (total > 0) {
                /**获取工商信息列表数组*/
                JSONArray items = baseInfo.getJSONArray("items");
                for (int i = 0; i < items.size(); i++) {
                    EcardApiAgricultureInfo agricultureInfo = new EcardApiAgricultureInfo();
                    agricultureInfo.setAgrLicenseName(items.getJSONObject(i).getString("name"));//营业执照名称
                    agricultureInfo.setAgrCreditCode(items.getJSONObject(i).getString("creditCode"));//统一社会信用编码
                    agricultureInfo.setAgrLegalPersonName(items.getJSONObject(i).getString("legalPersonName"));//经营者
                    String time = items.getJSONObject(i).getString("estiblishTime");
                    if (StringUtils.objIsNullOrEmpty(time)){
                        agricultureInfo.setAgrEstiblishTime(time); //成立日期
                    } else {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = null;
                        boolean dateFlag = true;
                        String estiblishTimeStr = "";
                        try {
                            date = sdf.parse(time);
                        } catch (ParseException e) {
                            dateFlag = false;
                        }
                        if (dateFlag) {
                            //日期合法转换，不合法存空
                            estiblishTimeStr = sdf.format(date);
                        }
                        agricultureInfo.setAgrEstiblishTime(estiblishTimeStr); //成立日期
                    }
                    agricultureInfo.setAgrRegCapital(items.getJSONObject(i).getString("regCapital"));//资金数额
                    agricultureInfo.setAgrRegStatus(items.getJSONObject(i).getString("regStatus"));//经营状态
                    agricultureInfoList.add(agricultureInfo);
                }
            }
        } else {
            return ResponseModel.error(responseModel.getMsg());
        }
        return ResponseModel.okToJSONArray(agricultureInfoList);
    }

   /**
    * 电子名片-调用天眼查接口查询获取工商联系方式接口
    *
    * @author yuzhiguo
    * @date 2024/11/7 下午2:54
    */
    @PostMapping(value = "/getAgricultureContactByTYC")
    @ApiOperation(value = "电子名片-调用天眼查接口查询获取工商联系方式接口", notes = "电子名片-调用天眼查接口查询获取工商联系方式接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getAgricultureContactByTYC(@RequestBody String json) {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        //接口编号
        String apiNum = ecardApiSysConfigService.selectConfigByKey("data.interfaceNum.orgContactSearch", dept.getDeptId());
        JSONObject jsonObject = JSONObject.parseObject(json);
        String agrLicenseName = jsonObject.getString("agrLicenseName");//营业执照名称
        if (StringUtils.objIsNullOrEmpty(agrLicenseName)) {
            return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
        }
        List<EcardApiAgricultureInfo> agricultureInfoList = new ArrayList<>();
        /**调用接口*/
        ResponseModel responseModel = ecardOrgInfoApiCommon.getOrgInfoByApi(userInfo, apiNum, agrLicenseName, "");
        if (responseModel.getCode() == 0) {
            JSONObject baseInfo = JSONObject.parseObject(JSON.toJSONString(responseModel.getData()));
            EcardApiAgricultureInfo agricultureInfo = new EcardApiAgricultureInfo();
            agricultureInfo.setAgrPhoneNumber(baseInfo.getString("phoneNumber"));//联系方式
            agricultureInfoList.add(agricultureInfo);
        } else {
            return ResponseModel.error(responseModel.getMsg());
        }
        return ResponseModel.okToJSONArray(agricultureInfoList);
    }

    /**
     * 电子名片-根据ID修改新型农业主体状态
     *
     * @author yuzhiguo
     * @date 2024/8/19 下午2:24
     */
    @PostMapping(value = "/changeAgricultureStatus")
    @ApiOperation(value = "电子名片-根据ID修改新型农业主体状态", notes = "电子名片-根据ID修改新型农业主体状态")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel changeAgricultureStatus(@RequestBody String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            int updateCount = ecardAgricultureInfoService.changeAgricultureStatus(id);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("删除失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

//-----------------------------------------------------------------以下为统计接口--------------------------------------------------------------------

    /**
     * 电子名片-我的新型农业主体建档拜访数量统计接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午9:38
     */
    @PostMapping(value = "/getAgrFilingVisitsStatistics")
    @ApiOperation(value = "电子名片-我的新型农业主体建档拜访数量统计接口", notes = "电子名片-我的新型农业主体建档拜访数量统计接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getAgrFilingVisitsStatistics() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardBranchAgricultureChartService.getAgrFilingVisitsStatistics(userInfo.getUserId());
            EcardBranchEcardChart ecardChart = new EcardBranchEcardChart();
            ecardChart.setMerchantNum(jsonObject.getLong("agrPerFilingNums"));//农业本人累计建档总数
            ecardChart.setVisitSum(jsonObject.getLong("agrPerVisitNums"));//农业本人累计拜访总数
            ecardChart.setDoTaskSum(jsonObject.getLong("agrPerDoVisitNums"));//农业本人超时拜访总数
            ecardChart.setUndoTaskSum(jsonObject.getLong("agrPerUnDoVisitNums"));//农业本人超时未拜访总数
            ecardChart.setMerchantMonthNum(jsonObject.getLong("agrPerFilingThisMonthNums"));//农业本人本月新增建档总数
            ecardChart.setMerchantLastMonthNum(jsonObject.getLong("agrPerFilingCompareNums"));//农业本人建档较上月对比
            ecardChart.setVisitMouthSum(jsonObject.getLong("agrPerVisitThisMonthNums"));//农业本人本月新增拜访总数
            ecardChart.setVisitLastMouthNum(jsonObject.getLong("agrPerVisitCompareNums"));//农业本人拜访较上月对比
            if (ecardChart.getMerchantLastMonthNum() >= 0){
                ecardChart.setCompareMerchantType("1");//较上月农业本人建档类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareMerchantType("2");//较上月农业本人建档类型（1：上升，2：下降）
            }
            if (ecardChart.getVisitLastMouthNum() >= 0){
                ecardChart.setCompareVisitType("1");//较上月农业本人拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareVisitType("2");//较上月农业本人拜访类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(ecardChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-全行新型农业主体建档拜访数量统计接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:03
     */
    @PostMapping(value = "/getAgrAllFilingVisitsNums")
    @ApiOperation(value = "电子名片-全行新型农业主体建档拜访数量统计接口", notes = "电子名片-全行新型农业主体建档拜访数量统计接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getAgrAllFilingVisitsNums() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardBranchAgricultureChartService.getAgrAllFilingVisitsNums(userInfo.getDeptId());
            EcardBranchEcardChart ecardChart = new EcardBranchEcardChart();
            ecardChart.setMerchantNum(jsonObject.getLong("agrFilingNums"));//全行农业建档总数
            ecardChart.setFilingLastMonthNums(jsonObject.getLong("agrFilingLastMonthNums"));//上月新增农业建档总数
            ecardChart.setMerchantMonthNum(jsonObject.getLong("agrFilingThisMonthNums"));//本月新增农业建档总数
            ecardChart.setMerchantLastMonthNum(jsonObject.getLong("agrFilingCompareNums"));//农业建档较上月对比
            ecardChart.setVisitSum(jsonObject.getLong("agrVisitNums"));//农业拜访总次数
            ecardChart.setVisitNewLastMonthNums(jsonObject.getLong("agrVisitLastMonthNums"));//上月新增农业拜访总数
            ecardChart.setVisitMouthSum(jsonObject.getLong("agrVisitThisMonthNums"));//本月新增农业拜访总数
            ecardChart.setVisitLastMouthNum(jsonObject.getLong("agrVisitCompareNums"));//农业拜访较上月对比
            if (ecardChart.getMerchantLastMonthNum() >= 0){
                ecardChart.setCompareMerchantType("1");//较上月农业建档类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareMerchantType("2");//较上月农业建档类型（1：上升，2：下降）
            }
            if (ecardChart.getVisitLastMouthNum() >= 0){
                ecardChart.setCompareVisitType("1");//较上月农业拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareVisitType("2");//较上月农业拜访类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(ecardChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-农业超时拜访数量统计接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:08
     */
    @PostMapping(value = "/getAgrTimeoutVisitsNums")
    @ApiOperation(value = "电子名片-农业超时拜访数量统计接口", notes = "电子名片-农业超时拜访数量统计接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getAgrTimeoutVisitsNums() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardBranchAgricultureChartService.getAgrTimeoutVisitsNums(userInfo.getDeptId());
            EcardBranchEcardChart ecardChart = new EcardBranchEcardChart();
            ecardChart.setDoTaskSum(jsonObject.getLong("agrDoTaskNums"));//农业超时拜访总数
            ecardChart.setDoTaskLastMonthNums(jsonObject.getLong("agrDoTaskLastMonthNums"));//上月新增农业超时拜访总数
            ecardChart.setDoTaskThisMonthNums(jsonObject.getLong("agrDoTaskThisMonthNums"));//本月新增农业超时拜访总数
            ecardChart.setDoTaskCompareNums(jsonObject.getLong("agrDoTaskCompareNums"));//农业超时拜访较上月对比
            ecardChart.setUndoTaskSum(jsonObject.getLong("agrUndoTaskNums"));//农业超时未拜访总次数
            ecardChart.setUndoTaskLastMonthNums(jsonObject.getLong("agrUndoTaskLastMonthNums"));//上月新增农业超时未拜访总数
            ecardChart.setUndoTaskThisMonthNums(jsonObject.getLong("agrUndoTaskThisMonthNums"));//本月新增农业超时未拜访总数
            ecardChart.setUndoTaskCompareNums(jsonObject.getLong("agrUndoTaskCompareNums"));//农业超时未拜访较上月对比
            if (ecardChart.getDoTaskCompareNums() >= 0){
                ecardChart.setCompareDoType("1");//较上月超时拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareDoType("2");//较上月超时拜访类型（1：上升，2：下降）
            }
            if (ecardChart.getUndoTaskCompareNums() >= 0){
                ecardChart.setCompareUndoType("1");//较上月超时未拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareUndoType("2");//较上月超时未拜访类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(ecardChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-查询农业建档折线图数据接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:10
     */
    @PostMapping(value = "/getAgrFilingLineChart")
    @ApiOperation(value = "电子名片-查询农业建档折线图数据接口", notes = "电子名片-查询农业建档折线图数据接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getAgrFilingLineChart() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            List<EcardBranchEcardChart> ecardBranchEcardChartList = ecardBranchAgricultureChartService.getAgrFilingLineChartByApplet(userInfo.getDeptId());
            return ResponseModel.okToJSONArray(ecardBranchEcardChartList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-查询农业拜访柱状图数据接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:13
     */
    @PostMapping(value = "/getaAgrVisitLineChart")
    @ApiOperation(value = "电子名片-查询农业拜访柱状图数据接口", notes = "电子名片-查询农业拜访柱状图数据接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getaAgrVisitLineChart() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            List<EcardBranchEcardChart> ecardBranchEcardChartList = ecardBranchAgricultureChartService.getAgrVisitLineChartByApplet(userInfo.getDeptId());
            return ResponseModel.okToJSONArray(ecardBranchEcardChartList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-各机构农业建档排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:15
     */
    @PostMapping(value = "/getAgrDeptFilingList")
    @ApiOperation(value = "电子名片-电子名片-各机构农业建档排名接口", notes = "电子名片-电子名片-各机构农业建档排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrDeptFilingList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptFiling ecardBranchDeptFiling = new EcardBranchDeptFiling();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptFiling.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptFiling.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptFiling> ecardBranchDeptFilingList = ecardBranchAgricultureChartService.getAgrDeptFilingList(ecardBranchDeptFiling);
            for (EcardBranchDeptFiling branchDeptFiling : ecardBranchDeptFilingList) {
                if (branchDeptFiling.getMerchantCompareNum() >= 0){
                    branchDeptFiling.setCompareType("1");//较上月类型（1：上升，2：下降）
                } else {
                    branchDeptFiling.setCompareType("2");//较上月类型（1：上升，2：下降）
                }
            }
            PageInfo pageInfo = new PageInfo(ecardBranchDeptFilingList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptFilingList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员农业建档排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:17
     */
    @PostMapping(value = "/getAgrUserFilingList")
    @ApiOperation(value = "电子名片-营销人员农业建档排名接口", notes = "电子名片-营销人员农业建档排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrUserFilingList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserFiling ecardBranchUserFiling = new EcardBranchUserFiling();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserFiling.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserFiling.setDeptId(sysDept.getDeptId());
            ecardBranchUserFiling.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserFiling.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserFiling> ecardBranchUserFilingList = ecardBranchAgricultureChartService.getAgrUserFilingList(ecardBranchUserFiling);
            PageInfo pageInfo = new PageInfo(ecardBranchUserFilingList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserFilingList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-机构农业拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:18
     */
    @PostMapping(value = "/getAgrDeptVisitsList")
    @ApiOperation(value = "电子名片-机构农业拜访次数排名接口", notes = "电子名片-机构农业拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrDeptVisitsList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptVisit ecardBranchDeptVisit = new EcardBranchDeptVisit();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptVisit.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptVisit.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptVisit> ecardBranchDeptVisitList = ecardBranchAgricultureChartService.getAgrDeptVisitsList(ecardBranchDeptVisit);
            for (EcardBranchDeptVisit branchDeptVisit : ecardBranchDeptVisitList) {
                if (branchDeptVisit.getVisitCompareNum() >= 0){
                    branchDeptVisit.setCompareType("1");//较上月类型（1：上升，2：下降）
                } else {
                    branchDeptVisit.setCompareType("2");//较上月类型（1：上升，2：下降）
                }
            }
            PageInfo pageInfo = new PageInfo(ecardBranchDeptVisitList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptVisitList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员农业拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:20
     */
    @PostMapping(value = "/getAgrUserVisitsList")
    @ApiOperation(value = "电子名片-营销人员农业拜访次数排名接口", notes = "电子名片-营销人员农业拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrUserVisitsList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserVisit ecardBranchUserVisit = new EcardBranchUserVisit();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserVisit.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserVisit.setDeptId(sysDept.getDeptId());
            ecardBranchUserVisit.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserVisit.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserVisit> ecardBranchUserVisitList = ecardBranchAgricultureChartService.getAgrUserVisitsList(ecardBranchUserVisit);
            PageInfo pageInfo = new PageInfo(ecardBranchUserVisitList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserVisitList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-机构农业超时拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:22
     */
    @PostMapping(value = "/getAgrDeptDoTaskList")
    @ApiOperation(value = "电子名片-机构农业超时拜访次数排名接口", notes = "电子名片-机构农业超时拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrDeptDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptDoTask ecardBranchDeptDoTask = new EcardBranchDeptDoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptDoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptDoTask.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptDoTask> ecardBranchDeptDoTaskList = ecardBranchAgricultureChartService.getAgrDeptDoTaskList(ecardBranchDeptDoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchDeptDoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptDoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-机构农业超时未拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:24
     */
    @PostMapping(value = "/getAgrDeptUnDoTaskList")
    @ApiOperation(value = "电子名片-机构农业超时未拜访次数排名接口", notes = "电子名片-机构农业超时未拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrDeptUnDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptUndoTask ecardBranchDeptUndoTask = new EcardBranchDeptUndoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptUndoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptUndoTask.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptUndoTask> ecardBranchDeptUndoTaskList = ecardBranchAgricultureChartService.getAgrDeptUnDoTaskList(ecardBranchDeptUndoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchDeptUndoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptUndoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员农业超时拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:27
     */
    @PostMapping(value = "/getAgrUserDoTaskList")
    @ApiOperation(value = "电子名片-营销人员农业超时拜访次数排名接口", notes = "电子名片-营销人员农业超时拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrUserDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserDoTask ecardBranchUserDoTask = new EcardBranchUserDoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserDoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserDoTask.setDeptId(sysDept.getDeptId());
            ecardBranchUserDoTask.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserDoTask.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserDoTask> ecardBranchUserDoTaskList = ecardBranchAgricultureChartService.getAgrUserDoTaskList(ecardBranchUserDoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchUserDoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserDoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员农业超时未拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/11/1 上午10:29
     */
    @PostMapping(value = "/getAgrUserUnDoTaskList")
    @ApiOperation(value = "电子名片-营销人员农业超时未拜访次数排名接口", notes = "电子名片-营销人员农业超时未拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getAgrUserUnDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserUndoTask ecardBranchUserUndoTask = new EcardBranchUserUndoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserUndoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserUndoTask.setDeptId(sysDept.getDeptId());
            ecardBranchUserUndoTask.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserUndoTask.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserUndoTask> ecardBranchUserUndoTaskList = ecardBranchAgricultureChartService.getAgrUserUnDoTaskList(ecardBranchUserUndoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchUserUndoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserUndoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }
}
